package controlComponents;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Rectangle;
import java.util.LinkedList;

import javax.swing.JLabel;
import javax.swing.JPanel;

import constants.Constants;

public class WindowViewer implements ScaleWriter {

	private JPanel threadPanel;
	private double nextData = 0;
	private String nextTime = new String();
	private JLabel windowOpen, windowClosed;
	private int windowStatus = -1;
	private int ID;
	private LinkedList<Information> list = new LinkedList<Information>();

	public WindowViewer(int id) {
		this.ID = id;
		list = new LinkedList<Information>();
		windowStatus = -1;
		windowOpen = new JLabel("Window Open");
		windowClosed = new JLabel("Window Closed");
		windowOpen.setForeground(Constants.green);
		windowOpen.setFont(new Font("SansSerif", Font.BOLD, 14));
		windowOpen.setBounds(new Rectangle(5, 5, 150, 30));
		windowClosed.setBounds(new Rectangle(5, 5, 150, 30));
		windowClosed.setForeground(Color.red);
		windowClosed.setFont(new Font("SansSerif", Font.BOLD, 14));
	}

	@Override
	public void run() {

		Information i;
		while (list.size() > 0 || (hasFinished == false && list.size() < 1)) {
			while (list.size() < 1) {
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			i = list.poll();
			nextData = i.getData();
			nextTime = i.getTime();
			if ((int) nextData == 0) {
				if (windowStatus == 0)
					;
				else {
					windowStatus = 0;
					modifyPanel(windowStatus, nextTime);
				}
			}
			if ((int) nextData == 1) {
				if (windowStatus == 1)
					;
				else {
					windowStatus = 1;
					modifyPanel(windowStatus, nextTime);
				}
			}

		}

	}

	private void modifyPanel(int type, String time) {
		threadPanel.removeAll();
		switch (type) {
		case 0: {
			windowClosed.setToolTipText("Window Closed at " + time);
			windowClosed.repaint();
			threadPanel.add(windowClosed, null);
			break;
		}
		case 1: {
			windowOpen.setToolTipText("Window opened at " + time);
			windowOpen.repaint();
			threadPanel.add(windowOpen, null);
			break;
		}
		}

		threadPanel.setPreferredSize(new Dimension(100, size));
		threadPanel.setSize(new Dimension(100, size));
		threadPanel.repaint();
	}

	@Override
	public void writeNext(Information i) {
		list.add(i);
	}

	@Override
	public void setPanel(JPanel panel) {
		threadPanel = panel;

	}

	private boolean hasFinished = false;

	@Override
	public void finished() {
		hasFinished = true;
	}

}